package com.project.server.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.server.common.api.Result;
import com.project.server.entity.HealthRecord;
import com.project.server.service.HealthRecordService;
import com.project.server.vo.HealthReportVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/health-records")
public class HealthRecordController extends BaseController {

    @Autowired
    private HealthRecordService healthRecordService;

    @GetMapping("/list")
    public Result<Page<HealthRecord>> getList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer type,
            HttpServletRequest request) {
        return Result.success(healthRecordService.getRecordList(getCurrentUserId(request), current, size, type));
    }

    @PostMapping
    public Result<Void> addRecord(@RequestBody HealthRecord record, HttpServletRequest request) {
        record.setUserId(getCurrentUserId(request));
        healthRecordService.addRecord(record);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteRecord(@PathVariable Long id, HttpServletRequest request) {
        healthRecordService.deleteRecord(id);
        return Result.success();
    }

    @GetMapping("/export")
    public void exportRecords(
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request,
            HttpServletResponse response) {
        healthRecordService.exportRecords(getCurrentUserId(request), type, startDate, endDate, response);
    }

    @GetMapping("/report")
    public Result<HealthReportVO> getHealthReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request) {
        return Result.success(healthRecordService.generateHealthReport(getCurrentUserId(request), startDate, endDate));
    }

    @GetMapping("/latest")
    public Result<List<HealthRecord>> getLatestRecords(HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        List<HealthRecord> records = healthRecordService.getLatestRecords(userId);
        return Result.success(records);
    }

}
